//
//  BHSettingUtil.m
//  Behing
//
//  Created by Lj on 2017/9/27.
//  Copyright © 2017年 lj. All rights reserved.
//

#import "BHSettingUtil.h"
#import "YYLabel.h"
#import "YYText.h"
#import <CommonCrypto/CommonDigest.h>


@implementation BHSettingUtil

// 给某个view添加手势
+ (void)addTapGestureInView:(UIView *)inView addTarget:(id)target action:(SEL)action withTag:(NSInteger)viewTag {
    inView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:target action:action];
    [tapGesture setCancelsTouchesInView:NO];
    tapGesture.numberOfTapsRequired = 1;
    inView.tag = viewTag;
    [inView addGestureRecognizer:tapGesture];
}

//给某个view添加黑白渐变
+ (void)addGradient:(UIView *)inView alpha:(CGFloat)alpha {
    UIColor *colorOne = [UIColor colorWithRed:(0.0/255.0)  green:(0/255.0)  blue:(0.0/255.0)  alpha:alpha];
    UIColor *colorTwo = [UIColor colorWithRed:(0.0/255.0)  green:(0/255.0)  blue:(0/255.0)  alpha:0.0];
    NSArray *colors = [NSArray arrayWithObjects:(id)colorOne.CGColor, colorTwo.CGColor, nil];
    CAGradientLayer *gradient = [CAGradientLayer layer];
    //设置开始和结束位置(设置渐变的方向)
    gradient.startPoint = CGPointMake(0, 0);
    gradient.endPoint = CGPointMake(0, 1);
    gradient.colors = colors;
    gradient.frame = inView.bounds;
    [inView.layer insertSublayer:gradient atIndex:0];
}

// 判断数据是否为空或空对象(如果字符串的话是否为@"")
+ (BOOL)dataAndStringIsNull:(id)string {
    if ([string isEqual:[NSNull null]] || string == nil || [string isEqual:@""]) {
        return YES;
    }
    return NO;
}

/** 设置label的 部分字体的颜色大小 */
+ (void)setAttributeLabel:(UILabel *)label font:(UIFont *)font color:(UIColor *)color rangeArray:(NSArray *)array {
    if (label.text != nil) {
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:label.text];
        for (NSString *string in array) {
            NSRange range = [label.text rangeOfString:string];
            //设置字号
            [str addAttribute:NSFontAttributeName value:font range:range];
            //设置颜色
            [str addAttribute:NSForegroundColorAttributeName value:color range:range];
        }
        label.attributedText = str;
    }
}

//计算Label的宽度
+ (CGFloat)widthForText:(NSString *)string fontSize:(CGFloat)fontSize {
    CGSize size =[string sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize * SizeScale]}];
    return size.width + 20;
}

// 设置label的attributedText行间距
+ (NSMutableAttributedString *)allocLabelattributedTextLineSpace:(CGFloat)lineSpace withLabelText:(NSString *)labelText {
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpace];
    
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
    return attributedString;
}

/** 计算Lbale的高度 */
+ (CGFloat)heightForText:(NSString *)string font:(UIFont *)font maxWidth:(CGFloat)maxWidth withTextLineSpace:(CGFloat)textLineSpace {
    NSMutableAttributedString *attrStr;
    if ([self dataAndStringIsNull:string]) return 0;
    if (textLineSpace == 0)
        attrStr = [[NSMutableAttributedString alloc] initWithString:string];
    else
        attrStr = [self allocLabelattributedTextLineSpace:textLineSpace withLabelText:string];
    NSRange allRange = [string rangeOfString:string];
    [attrStr addAttribute:NSFontAttributeName
                    value:font
                    range:allRange];
    [attrStr addAttribute:NSForegroundColorAttributeName
                    value:[UIColor darkGrayColor]
                    range:allRange];
    CGFloat titleHeight;
    NSStringDrawingOptions options =  NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX)
                                        options:options
                                        context:nil];
    titleHeight = ceilf(rect.size.height);
    return titleHeight;
}

+ (CGFloat)LabelStrHeight:(NSString *)labelStr font:(UIFont *)font sizeWidth:(CGFloat)width maximumNumber:(CGFloat)height {
    if ([BHSettingUtil dataAndStringIsNull:labelStr]) return 0;
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc]initWithString:labelStr];
    attributedStr.yy_font = font;
    attributedStr.yy_lineSpacing = 5;
    YYTextLayout *textLayout = [YYTextLayout layoutWithContainerSize:CGSizeMake(width, height) text:attributedStr];
    return textLayout.textBoundingSize.height;
}

//时间戳转换成时间字符串
+ (NSString *)conversionTime:(NSString *)string dateFormat:(NSString *)format {
    if ([self dataAndStringIsNull:string]) return @"";
    else if ([string rangeOfString:@"Date"].location != NSNotFound) {
        NSRange start = [string rangeOfString:@"("];
        NSRange end = [string rangeOfString:@")"];
        
        NSString *sub = [string substringWithRange:NSMakeRange(start.location + 1, end.location - start.location - 4)];
        NSTimeInterval time = [sub doubleValue];
        NSDate *detaildate = [NSDate dateWithTimeIntervalSince1970:time];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
        [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
        [dateFormatter setDateFormat:format];
        NSString *currentDateStr = [dateFormatter stringFromDate:detaildate];
        return currentDateStr;
    }else return string;
}

+ (void)HTMLTextDocumentStr:(void(^)(NSMutableAttributedString *attributedStr, CGFloat height))callbackBlock htmlStr:(NSString *)htmlStr {
    if ([self dataAndStringIsNull:htmlStr]) {
        return;
    }
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *header = [NSString stringWithFormat:@"<html><head><meta name=\"viewport\" content=\"initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width\"><title></title><style>img {width: %f;margin:0;padding:0;}</style></head><body>",App_Frame_Width - 30];
        
        NSString *footer = @"</body></html>";
        NSString *str = [NSString stringWithFormat:@"%@%@%@",header,htmlStr,footer];
        
        NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithData:[str dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];
        [attrString addAttributes:@{NSBaselineOffsetAttributeName: @(0),//设置基线偏移值，取值为 NSNumber （float）,正值上偏，负值下偏，可使UILabel文本垂直居中
                                    NSFontAttributeName:[UIFont systemFontOfSize:15]} range:NSMakeRange(0, attrString.length)];
        CGFloat height = [attrString boundingRectWithSize:CGSizeMake(App_Frame_Width - 30, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size.height;
        dispatch_async(dispatch_get_main_queue(), ^{
            //回到主线程进行UI跟新
            callbackBlock(attrString,height);
        });
    });
}

/** 获取当前时间 */
+ (NSString *)fetchCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *newDate = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:newDate];
    return currentTimeString;
}

/** 计算金额 */
+ (NSString *)amountConversion:(NSString *)price {
    if ([self dataAndStringIsNull:price])
        return nil;
    
    NSString *setPrice;
    CGFloat getPrice = [price floatValue];
    if (getPrice >= 0.0f && getPrice < 10000.0f) {
        setPrice = [NSString stringWithFormat:@"%@元",@(price.floatValue)];
    }else if (getPrice >= 10000.f && getPrice < powf(10, 8)) {
        setPrice = [NSString stringWithFormat:@"%@万",@([NSString stringWithFormat:@"%.2f",getPrice/10000.f].floatValue)];
    }else if (getPrice >= powf(10, 8) && getPrice < powf(10, 18)) {
        setPrice = [NSString stringWithFormat:@"%.2f亿",getPrice/100000000.f];
    }
    return setPrice;
}

/** 输入金额的判断 */
+ (BOOL)isInputAmountConversion:(NSString *)price textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range{
    NSString *NumbersWithDot = @".1234567890";
    NSString *NumbersWithoutDot = @"1234567890";
    
    // 判断是否输入内容，或者用户点击的是键盘的删除按钮
    if (![price isEqualToString:@""]) {
        NSCharacterSet *cs;
        // 小数点在字符串中的位置 第一个数字从0位置开始
        NSInteger dotLocation = [textField.text rangeOfString:@"."].location;
        // 判断字符串中是否有小数点
        // NSNotFound 表示请求操作的某个内容或者item没有发现，或者不存在
        // range.location 表示的是当前输入的内容在整个字符串中的位置，位置编号从0开始
        if (dotLocation == NSNotFound ) {
            // -- 如果限制非第一位才能输入小数点，加上 && range.location != 0
            // 取只包含“myDotNumbers”中包含的内容，其余内容都被去掉
            /*
             [NSCharacterSet characterSetWithCharactersInString:myDotNumbers]的作用是去掉"myDotNumbers"中包含的所有内容，只要字符串中有内容与"myDotNumbers"中的部分内容相同都会被舍去
             在上述方法的末尾加上invertedSet就会使作用颠倒，只取与“myDotNumbers”中内容相同的字符
             */
            cs = [[NSCharacterSet characterSetWithCharactersInString:NumbersWithDot] invertedSet];
            if (range.location >= 9) {
                NSLog(@"单笔金额不能超过亿位");
                if ([price isEqualToString:@"."] && range.location == 9) return YES;
                else return NO;
            }
        }else cs = [[NSCharacterSet characterSetWithCharactersInString:NumbersWithoutDot] invertedSet];
        // 按cs分离出数组,数组按@""分离出字符串
        NSString *filtered = [[price componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        BOOL basicTest = [price isEqualToString:filtered];
        if (!basicTest)  return NO;
        if (dotLocation != NSNotFound && range.location > dotLocation + 2) return NO;
        if (textField.text.length > 11) return NO;
    }
    return YES;
}


//密码判断
+ (BOOL)validatePassword:(NSString *)passWord {
    NSString *passWordRegex = @"^(?![0-9]+$)(?![a-zA-Z]+$)(?![^0-9a-zA-Z]+$).{6,12}$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    return [passWordPredicate evaluateWithObject:passWord];
}


+ (void)transitformShowView:(UIView *)view hiddenView:(UIView *)toView completion:(void(^)(BOOL finished))finished {
    NSInteger indexView = [view.superview.subviews indexOfObject:view];
    NSInteger indexToView = [view.superview.subviews indexOfObject:toView];
    double delayInSeconds = 0.01;

    [UIView beginAnimations:@"tranTwoViewAnimation" context:nil];
    //设置时常
    [UIView setAnimationDuration:delayInSeconds];
    //设置动画淡入淡出
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    //设置代理
    [UIView setAnimationDelegate:self];

    //设置翻转方向
    [UIView setAnimationTransition:indexView > indexToView ?  UIViewAnimationTransitionFlipFromRight :UIViewAnimationTransitionFlipFromLeft forView:view.superview cache:YES];
    
    [view.superview exchangeSubviewAtIndex:indexView withSubviewAtIndex:indexToView];
    //动画结束
    [UIView commitAnimations];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        finished(YES);
    });
}

+ (NSString *) MD5:(NSString *)str {
    const char *cStr = [str UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, (unsigned int)strlen(cStr), digest );
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02X", digest[i]];
    
    return output;
}

@end
